package patternRecognition;

import java.io.File;
import java.util.ArrayList;

import recordProcessing.RecordParser;

import main.Main;
import fileProcessing.ParsingException;

public class QueryForVerticalRecords extends PatternQuery implements Runnable{
	
	

	public QueryForVerticalRecords(File f) {
		super(f);
	}
	/**
	 * 
	 * @throws ParsingException
	 */
	public void performAnalysis() throws ParsingException{
		analyzeFile();
		
		int temp;
		ArrayList<Integer> countOfFields = new ArrayList<Integer>();
		ArrayList<String> wordIterator = new ArrayList<String>();
		
		//look for fields repeated as the first word in a line
		String s1;
		for(ArrayList<String> row : wordsByRow){
			s1 = row.get(0);
			if(wordIterator.isEmpty()){//if first field found add to list with a count of 1
				wordIterator.add(s1);
				countOfFields.add(1);
			}					
			else{
				if(wordIterator.contains(s1)){//else if field already exists, increment the count
					temp = wordIterator.indexOf(s1);
					countOfFields.set(temp, countOfFields.get(temp)+1);
				}
				else{//else add to list with count of 1
					wordIterator.add(s1);
					countOfFields.add(1);
				}
			}
		}
		
		int tempno=0,inc=0;
		for(int i : countOfFields){
			if(i>tempno)//find words with a high frequency of repetition "most likely a field"
				tempno=i;
		}
		for(String s : wordIterator){
			if(countOfFields.get(inc)==tempno){//identify all lines that have equal repetition to the max frequency
				fields.add(s);
			}
			inc++;
		}
		
		String val;
		for(ArrayList<String> sArray : wordsByRow){
			val="";
			if(fields.contains(sArray.get(0))){
				if(sArray.size()> 2){
					for(int i=1;i<sArray.size();i++){
						val+=(sArray.get(i)+" ");
					}
					val = val.substring(0, (val.length()-1));
				}
				else{
					if(sArray.size() == 2)
						val=sArray.get(1);
				}
				data.add(val);
			}
		}
	}
	@Override
	public void run() {
		try {
			performAnalysis();
			RecordParser.threadCount++;
		} catch (ParsingException e) {
			try {
				Main.audit.writeToAudit(e.getMessage());
			} catch (ParsingException e1) {
			}
		}
	}
}